//
//  JCReportMemberVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/12/2.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCReportMemberVC.h"
#import "JCClubMemberCell.h"
#import "JCClubInfoSectionHeader.h"
#import "JCClubApi.h"
#import "ClubsSetting.h"
#import "JCClubMemberModel.h"
#import "JCReportVC.h"
#import "YFAlertHelper.h"
#import "JCClubReportMemberListAlertView.h"

@interface JCReportMemberVC ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *input;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) ReportMemberListType memberListType;
@property (strong, nonatomic) NSMutableArray <JCClubMemberModel *> *memberList;
@property (strong, nonatomic) NSArray *result;

@end

@implementation JCReportMemberVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getReportMemberListForClubID:_clubID reportMemberListType:_memberListType complete:^(NSError *error, NSArray<JCClubMemberModel *> *memberList) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.memberList removeAllObjects];
            [weakSelf.memberList addObjectsFromArray:memberList];
            [weakSelf.memberList sortUsingComparator:^NSComparisonResult(JCClubMemberModel  *obj1, JCClubMemberModel  *obj2) {
                return [obj1.userName compare:obj2.userName];
            }];
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)initCode{
    _memberList = [NSMutableArray array];
    _input.attributedPlaceholder = [self creatAttributedString:@"Search member name" font:kOpenSansFont(OpenSansRegular, 16) color:UIColorFromHex(0x999999)];
    [_tableView registerClass:[JCClubInfoSectionHeader class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([JCClubInfoSectionHeader class])];
    [_input addTarget:self action:@selector(inputChanged:) forControlEvents:UIControlEventEditingChanged];
    _memberListType = ReportMemberListTypeLastWeek;
}

- (void)inputChanged:(UITextField *)tf{
    _result = [self searchText:tf.text dataArray:_memberList];
    [_tableView reloadData];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return YES;
}

- (NSArray *) searchText:( NSString *)text dataArray:(NSArray *)dataArray{
    if ([text isEqualToString:@""]) {
        return dataArray;
    }
    NSPredicate *result = [NSPredicate predicateWithFormat:@"userName CONTAINS[cd] %@",text];
    return [dataArray filteredArrayUsingPredicate:result];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _result?_result.count:_memberList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCClubMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCClubMemberCell class]) forIndexPath:indexPath];
    [cell memberModel:_result?_result[indexPath.row]:_memberList[indexPath.row]
            indexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kSectionHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    __weak typeof(self)weakSelf = self;
    JCClubInfoSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([JCClubInfoSectionHeader class])];
    header.rightButtonAction = ^(SectionButtonType type){
        weakSelf.memberListType = !weakSelf.memberListType;
        [weakSelf loadData];
    };
    
    [header setleftTitle:@"Finish Week's Plan"];
    [header setRightTitle:_memberListType == ReportMemberListTypeAll?@"Total Time":@"Last Week"];
    header.buttonType = SectionButtonTypeSetup;
    return header;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        CGFloat sectionHeaderHeight = kSectionHeaderHeight;
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

- (IBAction)explainAction:(UIButton *)sender {
    [_input resignFirstResponder];
    JCClubReportMemberListAlertView *alertView = [[UINib nibWithNibName:NSStringFromClass([JCClubReportMemberListAlertView class]) bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    PopupViewController *popVC = [YFAlertHelper showPresentInView:nil alertView:alertView withAlertViewFrame:CGRectMake(0, 0, 280, 307) animationType:DetailViewControllerPresentAnimationTypeDown tapMaskViewDismiss:YES];
    __weak typeof(popVC)weakPopVC = popVC;
    alertView.dismissHandle = ^{
        [weakPopVC dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
}

- (IBAction)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kSegueShowReportList]) {
        JCReportVC *reportListVC = [segue destinationViewController];
        JCClubMemberCell *cell = sender;
        reportListVC.userID = [cell getMemberModel].userID;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


@end
